using System;
using System.Collections;
using System.Collections.Generic;
using GameLogic.AbilitySystem.Attribute;
using UnityEditor;
using UnityEngine;
using UriFormat = System.UriFormat;


namespace GameBaseFramework.Extension
{
    /// <summary>
    /// 可序列化字典
    /// </summary>
    /// <typeparam name="TKey"></typeparam>
    /// <typeparam name="TValue"></typeparam>
    [Serializable]
    public class SerializationDic<TKey, TValue> : Dictionary<TKey, TValue>, ISerializationCallbackReceiver
    {
        [SerializeField]
        List<TKey> keys = new(10);

        [SerializeField]
        List<TValue> values = new(10);

        public void OnBeforeSerialize()
        {
            keys.Clear();
            values.Clear();
            if (Keys.IsNullOrEmpty())
            {
                return;
            }

            if (values.IsNullOrEmpty())
            {
                return;
            }

            keys = new List<TKey>(Keys);
            values = new List<TValue>(Values);
        }

        public void OnAfterDeserialize()
        {
            Clear();
            if (keys.IsNull() || values.IsNull()) return;
            var count = Math.Min(keys.Count, values.Count);
            for (var i = 0; i < count; ++i)
            {
                Add(keys[i], values[i]);
            }
        }
    }

    [CustomEditor(typeof(SerializationDic<AttributeType, AttributeModifier>))]
    public class SerializationDicEditor : Editor
    {
        public override void OnInspectorGUI()
        {
            //更新数据
            serializedObject.Update();
            SerializedProperty propertyKey = serializedObject.FindProperty("keys");
            SerializedProperty propertyValue = serializedObject.FindProperty("values");
            int size = propertyKey.arraySize;
            GUILayout.BeginVertical();
            for (int i = 0; i < size; i++)
            {
                GUILayout.BeginHorizontal();
                SerializedProperty key = propertyKey.GetArrayElementAtIndex(i);
                SerializedProperty value = propertyValue.GetArrayElementAtIndex(i);
                key.stringValue = EditorGUILayout.TextField("key", key.stringValue);
                value.stringValue = EditorGUILayout.TextField("value", value.stringValue);
                GUILayout.EndHorizontal();
            }
            GUILayout.EndVertical();
            //保存数据
            serializedObject.ApplyModifiedProperties();
        }
    }
}